/**
 * @author 黄波
 * 创建日期：2011Oct 16, 2011
 * TODO// N/A
 */
package com.platform.res.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.platform.constant.SaveDir;
import com.platform.pojo.TmpRes;
import com.platform.pojo.UserInfo;
import com.platform.res.bo.ResBo;

/**
 * 上传临时资源
 */
public class UploadTmpResAction extends ResourceSupport {

    /* 临时资源*/
    private File tmpRes;
    private String tmpResContentType;
    private String tmpResFileName;
    private String msg;
    private boolean success;
	private String getSavePath() throws Exception {
        return ServletActionContext.getRequest().getRealPath(SaveDir.TMP_RESOURCE_DIR);
    }
	@Override
	public String execute() throws Exception {
		//取前用户USERID
		HttpSession session = ServletActionContext.getRequest().getSession();
		UserInfo user = (UserInfo)session.getAttribute("user");
		if(user == null) {
			//用户未登录
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.flush();
			out.write("<script>alert('请登录后继续上传！');</script>");
			out.close();
			return null;
		}
		if(user.getIsAudit().intValue() != 1) {
			//用户未登录
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.flush();
			out.write("<script>alert('帐户锁定中，不能上传资源，请联系管理员解锁！');</script>");
			out.close();
			return null;
		}
		//加载系统配置文件
		String systemProfile = "/system.properties";
		InputStream stream = new FileInputStream(new File(ServletActionContext.getServletContext().getRealPath("/") + systemProfile));
		Properties properties = new Properties();
		properties.load(stream);
		stream.close();
		int tmpSize = Integer.parseInt(properties.get("tmp_size").toString());
        //上传资源icon
        if(tmpRes != null){
			//处理文件太大或不符规则等问题
			if(tmpRes.length() > tmpSize*1024*1024) {
		        msg = "暂存文件上传失败，文件过大！";
				HttpServletResponse response = ServletActionContext.getResponse();
				response.setCharacterEncoding("utf-8");
				response.setContentType("text/html");
				PrintWriter out = response.getWriter();
				out.flush();
				out.write("<script>alert('" + msg + "');</script>");
				out.close();
		        return null;
//		        Util.clearTMPFolder();
			} else {
				String tmpUrl = null;
				//此处使用UUID，防止文件重名
				File targetFile = new File(getSavePath() + "\\" + UUID.randomUUID().toString() + System.currentTimeMillis() + getTmpResFileName().substring(getTmpResFileName().indexOf(".")));
	//			File targetFile = new File(getSavePath() + "\\" + getUploadFileName()[i]);
				File targetDir = new File(getSavePath());
				if(!targetDir.exists()) {
					targetDir.mkdirs();
				}
				//文件重名则上能上传
				if(targetFile.exists()) {
			        msg = "资源缩略图上传失败，存在重名文件！";
				} else {
					if(!targetFile.exists()) {
						targetFile.createNewFile();
					}
					//以服务器的文件保存地址和原文件名建立上传文件输出流
					FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + targetFile.getName());
					FileInputStream fis = new FileInputStream(tmpRes);
					byte[] buffer = new byte[1024];
					int len = 0;
					while ((len = fis.read(buffer)) > 0){
						fos.write(buffer , 0 , len);
					}
			        fos.close();// 注意：流应当关闭。
			        fis.close();
			        tmpUrl = SaveDir.TMP_RESOURCE_DIR + "/" + targetFile.getName();
				}
				//上传成功，进行储存
				TmpRes tmpRes = new TmpRes();
				tmpRes.setName(getTmpResFileName());
				tmpRes.setUploadUserId(user.getId());
				tmpRes.setUrl(tmpUrl);
				tmpRes.setUploadTime(new Date());
				ResBo.getInstance().addTmpRes(tmpRes);
				HttpServletResponse response = ServletActionContext.getResponse();
				response.setCharacterEncoding("utf-8");
				response.setContentType("text/html");
				PrintWriter out = response.getWriter();
				out.flush();
				out.write("<script>alert('上传成功！');</script>");
				out.close();
		        return null;
			}
        }
        return null;
	}
	public File getTmpRes() {
		return tmpRes;
	}
	public void setTmpRes(File tmpRes) {
		this.tmpRes = tmpRes;
	}
	public String getTmpResContentType() {
		return tmpResContentType;
	}
	public void setTmpResContentType(String tmpResContentType) {
		this.tmpResContentType = tmpResContentType;
	}
	public String getTmpResFileName() {
		return tmpResFileName;
	}
	public void setTmpResFileName(String tmpResFileName) {
		this.tmpResFileName = tmpResFileName;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public boolean isSuccess() {
		return success;
	}
	public void setSuccess(boolean success) {
		this.success = success;
	}
    
}
